from pyproj import Transformer
from pyproj import CRS


def transform_coordinates(source_wkt, target_wkt, x, y, z=None):
    """
    将坐标从源坐标系转换到目标坐标系

    参数:
        source_wkt (str): 源坐标系的WKT定义
        target_wkt (str): 目标坐标系的WKT定义
        x (float): 源坐标系的X坐标
        y (float): 源坐标系的Y坐标
        z (float, optional): 源坐标系的Z坐标(可选)

    返回:
        tuple: 转换后的坐标(x, y)或(x, y, z)
    """
    # 从WKT创建CRS对象
    source_crs = CRS.from_wkt(source_wkt)
    target_crs = CRS.from_wkt(target_wkt)

    # 创建转换器
    transformer = Transformer.from_crs(source_crs, target_crs)

    # 执行转换
    if z is not None:
        transformed = transformer.transform(x, y, z)
        return transformed
    else:
        transformed = transformer.transform(x, y)
        return transformed


# 示例用法
if __name__ == "__main__":
    # 示例WKT定义 (这里使用WGS84和Web墨卡托作为示例)
    wgs84_wkt = 'GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563]], PRIMEM["Greenwich",0], UNIT["degree",0.0174532925199433]]'
    # wgs84_wkt = "GEOGCS[\"GCS_China_Geodetic_Coordinate_System_2000\",DATUM[\"D_China_2000\",SPHEROID[\"CGCS2000\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]"
    web_mercator_wkt = 'PROJCS["CGCS2000_3-degree_Gauss-Kruger", GEOGCS["CGCS2000", DATUM["CGCS2000", SPHEROID["GRS_1980",6378137,298.257222101]], PRIMEM["Greenwich",0], UNIT["degree",0.0174532925199433]], PROJECTION["Transverse_Mercator"], PARAMETER["latitude_of_origin",0], PARAMETER["central_meridian",118.5], PARAMETER["scale_factor",1], PARAMETER["false_easting",500000], PARAMETER["false_northing",0], UNIT["meter",1]]'

    # 要转换的坐标 (经度, 纬度)
    lon, lat = 118.076122, 31.719385  # 北京天安门坐标

    # 执行转换 (从WGS84经纬度到Web墨卡托)
    x, y = transform_coordinates(wgs84_wkt, web_mercator_wkt, lon, lat)
    print(f"Web墨卡托坐标: {x}, {y}")
    x1, y1 = 459824.76365022326, 3510814.753782486
    # 反向转换
    lon_back, lat_back = transform_coordinates(web_mercator_wkt, wgs84_wkt, x, y)
    print(f"转换回的经纬度: {lon_back:.6f}, {lat_back:.6f}")
